<template>
  <div class="dashboard-container">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1>欢迎使用报价工具系统</h1>
        <p>{{ welcomeMessage }}</p>
        <div class="current-time">{{ currentTime }}</div>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20" v-loading="statsLoading">
        <el-col :xs="12" :sm="6" v-for="(item, index) in statsData" :key="index">
          <div class="stat-card">
            <div class="stat-icon" :style="{ background: item.color }">
              <el-icon :size="24">
                <component :is="item.icon" />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ item.value }}</div>
              <div class="stat-title">{{ item.label }}</div>
              <div class="stat-trend" :class="item.trend > 0 ? 'trend-up' : 'trend-down'">
                <el-icon>
                  <ArrowUp v-if="item.trend > 0" />
                  <ArrowDown v-else />
                </el-icon>
                <span>{{ Math.abs(item.trend) }}%</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作区域 -->
    <div class="quick-actions-section">
      <h3>快速操作</h3>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" v-for="action in quickActions" :key="action.key">
          <div class="action-card" @click="handleQuickAction(action.route)">
            <div class="action-icon" :style="{ background: action.color }">
              <el-icon :size="28">
                <component :is="action.icon" />
              </el-icon>
            </div>
            <div class="action-content">
              <div class="action-title">{{ action.title }}</div>
              <div class="action-desc">{{ action.description }}</div>
            </div>
            <el-icon class="action-arrow">
              <ArrowRight />
            </el-icon>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 核价模块网格 -->
    <div class="modules-section">
      <h3>核价模块</h3>
      <el-row :gutter="20" v-loading="chartsLoading">
        <el-col :xs="12" :sm="8" :md="6" v-for="module in coreModules" :key="module.key">
          <div class="module-card" @click="handleModuleClick(module.route)">
            <div class="module-header">
              <div class="module-icon" :style="{ background: module.color }">
                <el-icon :size="24">
                  <component :is="module.icon" />
                </el-icon>
              </div>
              <div class="module-count">{{ module.count }}</div>
            </div>
            <div class="module-content">
              <div class="module-title">{{ module.title }}</div>
              <div class="module-desc">{{ module.description }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  Money,
  Document,
  List,
  SetUp,
  ArrowUp,
  ArrowDown,
  ArrowRight,
  Plus,
  Edit,
  View,
  Grid,
  TrendCharts,
  DataAnalysis,
  Connection,
  Coin
} from '@element-plus/icons-vue'
import {
  getDashboardStatsApi,
  getRecentActivitiesApi,
  getChartDataApi,
  getModuleStatsApi
} from '@/api/dashboard'
import type { ModuleStats, RecentActivity } from '@/api/dashboard/type.ts'
import type { Result } from '@/http/type'

// 注册必须的组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
])

const router = useRouter()

// 加载状态
const statsLoading = ref(true)
const chartsLoading = ref(true)
const tableLoading = ref(true)

// 当前时间和欢迎信息
const currentTime = ref('')
const welcomeMessage = ref('今天是个好日子，开始您的高效报价工作吧！')

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    weekday: 'long'
  })
}

// 统计数据
const statsData = ref([
  {
    key: 'totalQuotes',
    label: '总报价单数',
    value: '1,234',
    trend: 12,
    icon: Document,
    color: 'linear-gradient(135deg, #409EFF 0%, #66B3FF 100%)'
  },
  {
    key: 'monthlyQuotes', 
    label: '本月新增',
    value: '89',
    trend: 8,
    icon: Plus,
    color: 'linear-gradient(135deg, #67C23A 0%, #95D475 100%)'
  },
  {
    key: 'totalAmount',
    label: '总金额(万元)',
    value: '2,567',
    trend: -3,
    icon: Money,
    color: 'linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%)'
  },
  {
    key: 'avgAmount',
    label: '平均单价(元)',
    value: '15,678',
    trend: 5,
    icon: Coin,
    color: 'linear-gradient(135deg, #909399 0%, #B3B8C0 100%)'
  }
])

// 快速操作
const quickActions = ref([
  {
    key: 'newQuote',
    title: '结构件核价',
    description: '快速创建新的结构件核价',
    icon: Plus,
    color: 'linear-gradient(135deg, #67C23A 0%, #85CE61 100%)',
    route: '/specificationDetail'
  },
  {
    key: 'devicePricing',
    title: '设备核价',
    description: '进行设备价格核算',
    icon: Edit,
    color: 'linear-gradient(135deg, #409EFF 0%, #1989fa 100%)',
    route: '/devicePricing'
  },
  {
    key: 'budgetSheet',
    title: '预算单管理',
    description: '查看和管理预算单',
    icon: Document,
    color: 'linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%)',
    route: '/budgetSheet'
  },
  {
    key: 'historicalQuote',
    title: '历史报价',
    description: '查看历史报价记录',
    icon: View,
    color: 'linear-gradient(135deg, #909399 0%, #B3B8C0 100%)',
    route: '/historicalQuotation/index'
  }
])

// 核心模块
const coreModules = ref([
  {
    key: 'budgetSheet',
    title: '预算单',
    description: '项目预算管理与核算',
    icon: Document,
    color: 'linear-gradient(135deg, #409EFF 0%, #66B3FF 100%)',
    route: '/budgetSheet',
    count: 156
  },
  {
    key: 'devicePricing',
    title: '设备核价',
    description: '设备价格核算与管理',
    icon: SetUp,
    color: 'linear-gradient(135deg, #67C23A 0%, #95D475 100%)',
    route: '/devicePricing',
    count: 89
  },
  {
    key: 'softwarePlan',
    title: '软件核价',
    description: '软件系统价格规划',
    icon: Grid,
    color: 'linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%)',
    route: '/softwarePlan',
    count: 45
  },
  {
    key: 'conveyorPricing',
    title: '输送机核价',
    description: '输送设备价格核算',
    icon: Connection,
    color: 'linear-gradient(135deg, #F56C6C 0%, #FF7875 100%)',
    route: '/conveyorPricing',
    count: 78
  },
  {
    key: 'costPlan',
    title: '电控核价',
    description: '电控核价',
    icon: TrendCharts,
    color: 'linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%)',
    route: '/costPlan',
    count: 123
  },
  {
    key: 'increaseMachine',
    title: '提升机核价',
    description: '提升机核价',
    icon: Plus,
    color: 'linear-gradient(135deg, #FF9800 0%, #FFB74D 100%)',
    route: '/increaseMachinePricing',
    count: 34
  },
  {
    key: 'specificationDetail',
    title: '结构件核价',
    description: '结构件核价',
    icon: List,
    color: 'linear-gradient(135deg, #607D8B 0%, #90A4AE 100%)',
    route: '/specificationDetail',
    count: 267
  },
  {
    key: 'historicalQuotation',
    title: '历史报价',
    description: '历史报价记录查询',
    icon: DataAnalysis,
    color: 'linear-gradient(135deg, #795548 0%, #A1887F 100%)',
    route: '/historicalQuotation',
    count: 1234
  }
])

// 时间范围
const timeRange = ref('month')

// 最近报价记录
const recentQuotes = ref([
  {
    quoteNo: 'QT20240319001',
    title: '机械零件报价',
    amount: 156800,
    createTime: '2024-03-19 14:23',
    status: '已确认',
  },
  {
    quoteNo: 'QT20240319002',
    title: '电子元件报价',
    amount: 89500,
    createTime: '2024-03-19 11:35',
    status: '已提交',
  },
  {
    quoteNo: 'QT20240318003',
    title: '包装材料报价',
    amount: 45600,
    createTime: '2024-03-18 16:42',
    status: '草稿',
  },
  {
    quoteNo: 'QT20240318002',
    title: '五金配件报价',
    amount: 78900,
    createTime: '2024-03-18 15:20',
    status: '已确认',
  },
])

// 报价趋势图配置
const lineChartOption = {
  tooltip: {
    trigger: 'axis',
  },
  legend: {
    data: ['报价金额', '报价数量'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
  },
  yAxis: [
    {
      type: 'value',
      name: '金额(万)',
      position: 'left',
    },
    {
      type: 'value',
      name: '数量',
      position: 'right',
    },
  ],
  series: [
    {
      name: '报价金额',
      type: 'line',
      smooth: true,
      yAxisIndex: 0,
      data: [320, 280, 350, 420, 390, 380, 450],
      itemStyle: { color: '#409EFF' },
    },
    {
      name: '报价数量',
      type: 'line',
      smooth: true,
      yAxisIndex: 1,
      data: [15, 12, 18, 20, 16, 18, 22],
      itemStyle: { color: '#67C23A' },
    },
  ],
}

// 物料构成分析
const pieChartOption = {
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    left: 'left',
  },
  series: [
    {
      name: '物料类型',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 485, name: '原材料' },
        { value: 320, name: '半成品' },
        { value: 234, name: '成品' },
        { value: 158, name: '辅料' },
        { value: 89, name: '包装材料' },
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
}

// 获取状态对应的类型
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    草稿: 'info',
    已提交: 'warning',
    已确认: 'success',
  }
  return typeMap[status] || 'info'
}

// 处理快速操作点击
const handleQuickAction = (route: string) => {
  router.push(route)
}

// 处理模块点击
const handleModuleClick = (route: string) => {
  router.push(route)
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    // 加载统计数据
    const statsResult = await getDashboardStatsApi()
    console.log("statsResult:",statsResult)  
    
    // 检查返回结果是否有效
    if (statsResult && statsResult.code === 200 && statsResult.data) {
      const stats = statsResult.data
      // 更新统计卡片数据
      statsData.value[0].value = (stats.totalQuotes || 0).toLocaleString()
      statsData.value[1].value = (stats.monthlyQuotes || 0).toLocaleString()
      statsData.value[2].value = ((stats.totalAmount || 0)).toFixed(1) // 已经是万元
      statsData.value[3].value = (stats.avgAmount || 0).toLocaleString()
      
      // 更新趋势数据
      statsData.value[0].trend = stats.totalQuotesTrend || 0
      statsData.value[1].trend = stats.monthlyQuotesTrend || 0
      statsData.value[2].trend = stats.totalAmountTrend || 0
      statsData.value[3].trend = stats.avgAmountTrend || 0
    } else {
      console.error('统计数据获取失败:', statsResult)
    }
    
    // 加载模块统计数据
    const moduleResult = await getModuleStatsApi()
    if (moduleResult && moduleResult.code === 200 && moduleResult.data) {
      // 更新核心模块的count数据
      const statsMap: Record<string, number> = moduleResult.data as any
      coreModules.value.forEach(module => {
        if (statsMap[module.key] !== undefined) {
          module.count = statsMap[module.key]
        }
      })
    } else {
      console.error('模块统计数据获取失败:', moduleResult)
    }
    
    // 加载最近活动数据
    const activitiesResult = await getRecentActivitiesApi()
    if (activitiesResult && activitiesResult.code === 200 && activitiesResult.data && Array.isArray(activitiesResult.data)) {
      recentQuotes.value = activitiesResult.data.map((activity: RecentActivity) => ({
        quoteNo: `QT${activity.id.toString().padStart(8, '0')}`,
        title: activity.title,
        amount: parseInt(activity.description) || 0,
        createTime: activity.time,
        status: activity.type === 'create' ? '已提交' : '已确认'
      }))
    } else {
      console.error('最近活动数据获取失败:', activitiesResult)
    }
    
    console.log('仪表盘数据加载完成')
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  }
}

// 组件挂载
onMounted(() => {
  updateTime()
  // 每分钟更新一次时间
  setInterval(updateTime, 60000)
  
  // 分阶段加载数据
  nextTick(() => {
    setTimeout(() => {
      statsLoading.value = false
    }, 100)
    
    setTimeout(() => {
      chartsLoading.value = false
    }, 300)
    
    setTimeout(() => {
      tableLoading.value = false
    }, 500)
  })
  
  // 加载数据
  loadDashboardData()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  // 欢迎区域
  .welcome-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 30px;
    margin-bottom: 20px;
    color: white;
    text-align: center;

    .welcome-content {
      h1 {
        font-size: 28px;
        margin-bottom: 10px;
        font-weight: 600;
      }

      p {
        font-size: 16px;
        margin-bottom: 15px;
        opacity: 0.9;
      }

      .current-time {
        font-size: 14px;
        opacity: 0.8;
        font-weight: 500;
      }
    }
  }

  // 统计卡片区域
  .stats-section {
    margin-bottom: 30px;

    .stat-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      height: 100px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        color: white;
      }

      .stat-content {
        flex: 1;

        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #2c3e50;
          margin-bottom: 5px;
        }

        .stat-title {
          font-size: 14px;
          color: #7f8c8d;
          margin-bottom: 8px;
        }

        .stat-trend {
          display: flex;
          align-items: center;
          font-size: 12px;

          &.trend-up {
            color: #67c23a;
          }

          &.trend-down {
            color: #f56c6c;
          }

          span {
            margin-left: 4px;
            font-weight: 500;
          }
        }
      }
    }
  }

  // 快速操作区域
  .quick-actions-section {
    margin-bottom: 30px;

    h3 {
      font-size: 18px;
      color: #2c3e50;
      margin-bottom: 15px;
      font-weight: 600;
    }

    .action-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;
      height: 80px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      .action-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        color: white;
      }

      .action-content {
        flex: 1;

        .action-title {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
          margin-bottom: 5px;
        }

        .action-desc {
          font-size: 12px;
          color: #7f8c8d;
        }
      }

      .action-arrow {
        color: #bdc3c7;
        transition: color 0.3s ease;
      }

      &:hover .action-arrow {
        color: #409eff;
      }
    }
  }

  // 核价模块网格
  .modules-section {
    margin-bottom: 30px;

    h3 {
      font-size: 18px;
      color: #2c3e50;
      margin-bottom: 15px;
      font-weight: 600;
    }

    .module-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;
      height: 120px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      .module-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .module-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
        }

        .module-count {
          font-size: 18px;
          font-weight: 600;
          color: #409eff;
        }
      }

      .module-content {
        .module-title {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
          margin-bottom: 5px;
        }

        .module-desc {
          font-size: 12px;
          color: #7f8c8d;
          line-height: 1.4;
        }
      }
    }
  }

  // 图表卡片
  .chart-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h4 {
        font-size: 16px;
        color: #2c3e50;
        font-weight: 600;
        margin: 0;
      }
    }

    .chart-content {
      width: 100%;
    }
  }

  // 最近报价记录
  .recent-quotes-section {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        font-size: 18px;
        color: #2c3e50;
        margin: 0;
        font-weight: 600;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;

    .stats-section .stat-card {
      height: auto;
      flex-direction: column;
      text-align: center;
      padding: 15px;

      .stat-icon {
        margin-right: 0;
        margin-bottom: 10px;
      }
    }

    .action-card,
    .module-card {
      height: auto;
      padding: 15px;
    }

    .welcome-section {
      padding: 20px;

      .welcome-content h1 {
        font-size: 24px;
      }
    }
  }
}
</style>
